/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package GUI;

import Interaction.ServerConnection;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;

import Flightadministration.*;
import Data.*;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

/**
 *
 * @author David Ponce
 * @author Philipp Armbruster
 */
public class AirportManage extends JPanel{

    final Main td;
    public JPanel jp;
    public DefaultTableModel model;
    public JTable table;
    public Vector<Vector> rowData;
    public Vector<String> columnNames;
    public JButton button_CreateAirport;
    public GridBagConstraints constraints;
    public JScrollPane scrollPane;
    public int currentAirportId;
    final AirportEdit ae;
    /*Das AdministrationsObjekt, welches über die getConnection methode vom RMI Server geholt wird, dem "admin" objekt zugewiesen.
    *Dadurch ist eine Kommunikation zwischen GUI und Applikationsserver mittels RMI möglich*/
    final Flightadministration admin = ServerConnection.getConnection();


    // Konstruktor
    public AirportManage(final Main td, final AirportEdit ae)
                                throws java.rmi.RemoteException {

        this.td = td;
        this.ae = ae;
        showAirportManage();
    }


    // Methoden
    public void showAirportManage() throws RemoteException{

        jp = new JPanel();

        //GridBagLayout
        //**********************************************************************

        GridBagLayout gbl = new GridBagLayout();
        jp.setLayout(gbl);
        jp.setBackground(Color.white);

        constraints = new GridBagConstraints();

        constraints.fill = GridBagConstraints.HORIZONTAL;   // wie Komponente Bereich füllen soll
        constraints.weightx = 1;                     // Breite
        constraints.weighty = 1;                    // Höhe
        constraints.insets = new Insets(0,0,1,1);   // Abstände definieren

        //Label
        //**********************************************************************

        JLabel headline = new JLabel("<html><h2 color=blue>Übersicht aller Flughäfen</h2></html>");
        headline.setHorizontalAlignment(JLabel.CENTER);
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.gridwidth = 3;
        jp.add(headline, constraints);

        //JTable
        //**********************************************************************

        // Vector für Spaltenüberschrift mit Werten belegen
        columnNames = new Vector<String>();
        columnNames.add("Int. Kürzel");
        columnNames.add("Name");
        columnNames.add("Stadt");
        columnNames.add("Land");

        // Vector mit Daten für JTable belegen
        rowData = admin.getAllAirportsForTable();

        model = new DefaultTableModel( rowData, columnNames );
        model.addTableModelListener(table);
        table = new JTable(model) {
            public boolean isCellEditable(int x, int y) {
                return false;
            }
        };
        table.setModel(model);
        table.setAutoCreateRowSorter(true);
        table.getColumnModel().getColumn(0).setPreferredWidth(10);
        table.getColumnModel().getColumn(1).setPreferredWidth(150);
        table.getColumnModel().getColumn(2).setPreferredWidth(100);
        table.getColumnModel().getColumn(3).setPreferredWidth(100);
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.gridwidth = 3;
        table.setPreferredScrollableViewportSize(new Dimension(550,450));
        table.setVisible(true);
        scrollPane = new JScrollPane(table);
        jp.add( scrollPane, constraints);


        //Buttons
        //**********************************************************************

        button_CreateAirport = new JButton("Anlegen");
        constraints.gridwidth = 1;
        constraints.gridx = 0;
        constraints.gridy = 2;
        jp.add(button_CreateAirport, constraints);

        JButton button_EditAirport = new JButton("Editieren");
        constraints.gridwidth = 1;
        constraints.gridx = 1;
        constraints.gridy = 2;
        jp.add(button_EditAirport, constraints);

        JButton button_DeleteAirport = new JButton("Löschen");
        constraints.gridwidth = 1;
        constraints.gridx = 2;
        constraints.gridy = 2;
        jp.add(button_DeleteAirport, constraints);


        //ActionListener
        //**********************************************************************
        table.addMouseListener(new MouseAdapter(){
            @Override
            public void mouseClicked(MouseEvent evt){

                //Nur auf Doppelklick der linken Mousetaste reagieren.
                if(evt.getButton() == MouseEvent.BUTTON1 && evt.getClickCount() > 1){
                    edit();
                }
            }
        });

        button_CreateAirport.addActionListener(new ActionListener() {
                @Override
            public void actionPerformed(ActionEvent e){

                ((CardLayout) td.rightp.getLayout()).show(td.rightp, "AirportC");
            }
        });


        button_EditAirport.addActionListener(new ActionListener() {
                @Override
            public void actionPerformed(ActionEvent e){
                if (table.getSelectedRow()==-1) {
                    JOptionPane.showMessageDialog(null, "Bitte ein Element der Liste auswählen!");
                } else {
                    edit();
//                    int iSelectedRow = table.getSelectedRow();
//                    Object currentAirportIdasObject = table.getModel().getValueAt(iSelectedRow, 0);
//                       String currentAirportIdasString = String.valueOf(currentAirportIdasObject);
//
//                        try {
//                            Airport a = admin.getAirportById(currentAirportIdasString);
//
//                            ae.textfield1.setText(a.getPortName());
//                            ae.textfield2.setText(a.getInternationalId());
//                            ae.textfield3.setText(a.getPortCity());
//                            ae.textfield4.setText(a.getPortCountry());
//
//                            ((CardLayout) td.rightp.getLayout()).show(td.rightp, "AirportE");
//                        } catch (RemoteException ex) {
//                            Logger.getLogger(PassengerManage.class.getName()).log(Level.SEVERE, null, ex);
//                        }



                    ((CardLayout) td.rightp.getLayout()).show(td.rightp, "AirportE");
                }
            }
        });


        button_DeleteAirport.addActionListener(new ActionListener() {
                @Override
            public void actionPerformed(ActionEvent e){
                if (table.getSelectedRow()==-1) {
                    JOptionPane.showMessageDialog(null, "Bitte ein Element der Liste auswählen!");
                }
                else {
                    int iSelectedRow = table.getSelectedRow();

                    Object[] options = {"Ja", "Nein"};

                    String txt = "<html><p style=\"color:red; text-align: center\">Flughafen <i><u>"
                                + table.getModel().getValueAt(iSelectedRow, 1)
                                + " ("
                                + table.getModel().getValueAt(iSelectedRow, 2) + ")"
                                + "</i></u> wirklich löschen? <br>"
                                + "Dabei werden auch alle damit in Verbindung stehenden <br>"
                                + "Flüge, Flugdurchführungen und Buchungen gelöscht</p></html>";
                    int n = JOptionPane.showOptionDialog(td, txt, "Flughafen löschen",
                    JOptionPane.YES_NO_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    options,
                    options[1]);

                        if (n == 0) {
                            try {
                                // InternationalId des ausgewählten Flughafens auslesen
                                Object currentIntAirportId = table.getModel().getValueAt(iSelectedRow, 0);
                                    String currentIntAirportIdAsString = String.valueOf(currentIntAirportId);
                                // Namen des ausgewählten Flughafens auslesen
                                Object currentAirportName = table.getModel().getValueAt(iSelectedRow, 1);
                                    String currentAirportNameAsString = String.valueOf(currentAirportName);
                                // Stadt des ausgewählten Flughafens auslesen
                                Object currentAirportCity = table.getModel().getValueAt(iSelectedRow, 2);
                                    String currentAirportCityAsString = String.valueOf(currentAirportCity);
                                // Land des ausgewählten Flughafens auslesen
                                Object currentAirportCountry = table.getModel().getValueAt(iSelectedRow, 2);
                                    String currentAirportCountryAsString = String.valueOf(currentAirportCountry);

                                // Flughafenobjekt aus der Datenbank löschen
                                admin.deleteAirport(currentIntAirportIdAsString, currentAirportNameAsString,
                                                        currentAirportCityAsString, currentAirportCountryAsString);
                                    // JTables aktualisieren
                                    td.updateAirport();

                                JOptionPane.showMessageDialog(null, "Flughafen gelöscht");

                            } catch (RemoteException ex) {
                                Logger.getLogger(AirportManage.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                }
            }
        });

    }

    public void edit() {
                    int iSelectedRow = table.getSelectedRow();
                    Object currentAirportIdasObject = table.getModel().getValueAt(iSelectedRow, 0);
                       String currentAirportIdasString = String.valueOf(currentAirportIdasObject);

                        try {
                            Airport a = admin.getAirportById(currentAirportIdasString);

                            ae.label1.setText(a.getInternationalId());
                            ae.textfield1.setText(a.getPortName());
                            ae.textfield2.setText(a.getPortCity());
                            ae.textfield3.setText(a.getPortCountry());

                            ((CardLayout) td.rightp.getLayout()).show(td.rightp, "AirportE");
                        } catch (RemoteException ex) {
                            Logger.getLogger(PassengerManage.class.getName()).log(Level.SEVERE, null, ex);
                        }
    }

    public void updateTableData() throws RemoteException {

        // Vector mit Daten für JTable belegen
        rowData = admin.getAllAirportsForTable();

        // Tabelleninhalt wird aktualisiert
        model.setDataVector(rowData, columnNames);

    }

    public JPanel getJp() {
        return jp;
    }
}